//p82/457
package session2.casting;

public class DogTest {
	public static void main(String[] args) {
		Animal animal = new Animal();
		animal.makeNoise();

		// DOWN-CASTING; ERROR
		// Bi loi ClassCastException;
		try {
			// kieu con ep kieu cha;==>Ko the
			// ERR: session2.casting.Animal cannot be cast to
			// session2.casting.Dog
			Dog d = (Dog) animal;// Compiles OK but fails later;
			d.makeNoise();// khong loi nhung compile ERR;
		} catch (ClassCastException e) {
			System.out.println("exception: " + e.getMessage());
		}

		/**
		 * Both IS-A Animal, which means that anything an Animal can do, a Dog
		 * can do. A Dog can do more, of course,,, but the POINT is anyone with
		 * an Animal reference can safely call Animal methods on a Dog instance.
		 * Dog can always do at least everything an Animal can do. The compiler
		 * and JVM know it too, so the implicit UP-CAST is always legal for
		 * assigning an object of a sub-type to a reference of one of its
		 * super-type classes (for interfaces).
		 */

		// UP-CASTING; OKOKOK
		Dog d = new Dog();
		Animal a1 = d;
		a1.makeNoise();

		// UP-CASTING; OKOKOK
		Animal a2 = (Animal) d;
		a2.makeNoise();

		/**
		 * cha goi con; =>Cha co the dung method cua cha (duoc override o class
		 * con), cha khong the goi method cua class con (playDead()). Tru truong
		 * hop ep cha thanh con: ((Dog) a).playDead();
		 */
		Animal a = new Dog();
		a.makeNoise();
		((Dog) a).playDead();
	}
}